// pages/index/blessing.js
const config = require('../../config')
const util = require('../../utils/util')
var app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isme: false,    //是不是本人
        show_red_packet: false,  //是否显示红包发送界面
        red_packet_active: false, //选中红包内容
        isplay: false,  //是否正在播放
        is_gifted: false,   //是否给这个祝福发过红包
        allowpaly: true  //是否允许播放
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (e) {
      if (e.scene) {
        var id = decodeURIComponent(e.scene)
        this.animation = wx.createAnimation({
          timingFunction: 'ease-in-out'
        })
        this.innerAudioContext = wx.createInnerAudioContext()
        this.getinfo(id)
        this.setData({
          id: id
        })
      } else if (e.id) {
        var id = e.id
        this.animation = wx.createAnimation({
          timingFunction: 'ease-in-out'
        })
        this.innerAudioContext = wx.createInnerAudioContext()
        this.getinfo(id)
        this.setData({
          id: id
        })
       }else {
        wx.showModal({
          title: '非法请求',
          content: '非法请求',
          showCancel: false,
          success: function () {
            wx.reLaunch({
              url: '/pages/index/index',
            })
          }
        })
      }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    onHide: function () {
        var that = this
        that.innerAudioContext.pause()
        that.innerAudioContext.onPause(() => {
            that.setData({
                isplay: false
            })
        })
    },
    onUnload: function () {
        var that = this
        that.innerAudioContext.pause()
        that.innerAudioContext.onPause(() => {
            that.setData({
                isplay: false
            })
        })
    },
    //保存formid
    saveform: function (e) {
        var formid = e.detail.formId
        app.saveformid(formid)
    },
    getinfo: function(id){

        var that = this
        if (app.globalData.uid) {
            wx.showLoading({
                title: '加载中',
                mask:true
            })
            var headerkey = util.createheaderkey()
            wx.request({
                url: config.host + '/api/WishDetail/getWishDetail?',
                method: 'GET',
                header: {
                    'content-type': 'application/json',
                    'key': headerkey.key,
                    'time': headerkey.timestamp
                },
                data: {
                    uid: app.globalData.uid,
                    wid: id
                },
                success: function (res) {
                    if (res.data.code == 200) {
                        var data = res.data.data,
                            allowpaly = true  //是否自动播放
                        that.setData({
                            amount: data.amount,
                            count: data.count,
                            list: data.list,
                            mediadata: data.mediadata,
                            maxgift: data.maxgift,
                            red_packet_list: data.wishData,
                            is_gifted: data.is_gifted
                        })
                        //判断是否为本人
                        if (data.mediadata.id == app.globalData.uid){
                            that.setData({
                                isme : true
                            })
                        } else if (data.mediadata.needgift == 1 && data.is_gifted == 0) { //判断是否打开需要红包才能听，是否发送红包
                            allowpaly = false
                        }
 
                        that.setData({
                            allowpaly: allowpaly
                        })

                        if (data.mediadata.source_type == 1 ){

                            that.innerAudioContext.src = data.mediadata.source
                            //判断是否可以自动播放
                            if (allowpaly){
                                that.changestatus()
                                
                            }else{
                                wx.showToast({
                                    title: '发红包才能听哦',
                                })
                            }
                        }
                        wx.hideLoading()

                    }else{
                        wx.hideLoading()
                        wx.showModal({
                            title: '失败',
                            content: res.data.msg,
                            showCancel: false,
                            success: function () {
                                wx.navigateBack({})
                                
                            }
                        })
                    }
                },
                fail: function (res) {
                    wx.showToast({
                        title: '红包详情获取失败!',
                        duration: 3000
                    })
                }
            })
        } else {
            setTimeout(function () {
                that.getinfo(id)
            }, 1000)
        }
    },
    //修改音频播放状态
    changestatus: function () {
        var that = this
        if (that.data.isplay){
            
            that.innerAudioContext.pause()
            that.innerAudioContext.onPause(() => {
                that.setData({
                    isplay: false
                })
            })
            
        }else{

            //判断是否开启发了红包才能听，是不是已经发送红包  //并且不是本人
            if (!that.data.allowpaly && !that.data.isme){
                wx.showModal({
                    title: '需要发红包',
                    content: '主人设置了需要发送红包才可以听祝福哦，点击确定发一个红包给他吧',
                    success: function (res) {
                        if (res.confirm) {
                            that.red_packet_animation()
                        } 
                    }
                })
            }else{
                that.innerAudioContext.play()
                that.innerAudioContext.onPlay(() => {
                    that.setData({
                        isplay: true
                    })
                })
            }
            
        }
        that.innerAudioContext.onEnded(() => {
            //that.innerAudioContext.play()  //开启循环播放
            that.setData({ isplay: false })
        })
        
    },
    //举报
    report: function () {
        var wid = this.data.id,
            username = this.data.mediadata.name
        wx.navigateTo({
            url: '/pages/user/report?wid=' + wid + '&&username=' + username,
        })
    },
    //返回首页
    gotoindex:function(){
        wx.reLaunch({
            url: '/pages/index/index',
        })
    },

    //发红包动画
    red_packet_animation: function () {
        var show_red_packet = this.data.show_red_packet

        if (!show_red_packet) {

            this.setData({ show_red_packet: true })
            this.animation.translate(0, -650).step()
            this.setData({ red_packet: this.animation.export() })

        } else {

            this.setData({ show_red_packet: false })
            this.animation.translate(0, 650).step()
            this.setData({ red_packet: this.animation.export() })

        }
    },

    //选择红包金额
    active_red_packet:function(e){
        var that = this,
            index = e.currentTarget.dataset.index,
            red_packet_list = that.data.red_packet_list,
            red_packet_active = {
                key: index,
                money: red_packet_list[index].money,
                blessing: red_packet_list[index].blessing,
            }
        that.setData({
            red_packet_active: red_packet_active
        })
    },
    //输入修改红包金额
    moneychange: function (e) {

        var value = e.detail.value
        this.checkinput(value)
    },
    //检查输入项
    checkinput: function (value) {
        var red_packet_active = this.data.red_packet_active,
            maxgift = this.data.maxgift,
            isint = / ^\d+$/,
            isfloat = /^\d+(\.\d+)?$/
        //判断用户是否选中默认红包，没有选中的话，创建一个对象
        if (!red_packet_active) {
            red_packet_active = {}
        }
        //正则验证输入是否合法
        if (isint.test(value) || isfloat.test(value)) {
            value = parseFloat(value)
            value = value.toFixed(2)
            if (value < 1) {
                wx.showToast({
                    title: '最少发1元哦',
                })
                red_packet_active.money = 1

            } else if (value > maxgift) {
                wx.showToast({
                    title: '最多发' + maxgift + '元哦',
                })
                red_packet_active.money = maxgift
            }else{
                if (value.toString().split(".")[1].length > 2) {
                    wx.showToast({
                        title: '最多精确到2位数',
                    })
                    value = Math.round(value * 100) / 100;
                }
                red_packet_active.money = value
            }
        } else {

            wx.showToast({
                title: '数据不合法',
            })

            red_packet_active.money = 1
            
        }
        this.setData({
            red_packet_active: red_packet_active
        })
    },

    //验证输入金额
    validatemoney: function (value) {
        var maxgift = parseFloat(this.data.maxgift),
            red_packet_active = this.data.red_packet_active,
            value = parseFloat(value)
        if (value<1){
            
            wx.showToast({
                title: '最少发1元哦',
            })

            if (!red_packet_active) {
                red_packet_active = {}
            }
            red_packet_active.money = 1
            this.setData({
                red_packet_active: red_packet_active
            })
        } else if (value > maxgift){
            wx.showToast({
                title: '最多发' + maxgift + '元哦',
            })
            if (!red_packet_active) {
                red_packet_active = {}
            }
            red_packet_active.money = maxgift
            this.setData({
                red_packet_active: red_packet_active
            })
        }
        

    },
    //修改红包祝福语
    blessingchange:function(e){
        var red_packet_active = this.data.red_packet_active
        if (!red_packet_active) {
            red_packet_active = {}
        }
        red_packet_active.blessing = e.detail.value
        this.setData({
            red_packet_active: red_packet_active
        })

    },
    //发红包
    sendred_packet:function(){
        if (this.data.red_packet_active){
            var that = this,
                red_packet_active = that.data.red_packet_active,
                blessing, money,
                headerkey = util.createheaderkey()
            red_packet_active.money ? money = red_packet_active.money : money = 1
            red_packet_active.blessing ? blessing = red_packet_active.blessing : blessing = '恭喜发财，利是拿来'
            wx.request({
                url: config.host + '/api/sendwish/save',
                method: 'POST',
                header: {
                    'content-type': 'application/json',
                    'key': headerkey.key,
                    'time': headerkey.timestamp
                },
                data: {
                    sid: app.globalData.uid,
                    wid: that.data.id,
                    rid: that.data.mediadata.id,
                    blessing: blessing,
                    amount: money
                },
                success: function (res) {
                    if (res.data.code == 200) {
                        var data = res.data.data

                        wx.requestPayment({
                            'timeStamp': data.timeStamp,
                            'nonceStr': data.nonceStr,
                            'package': data.package,
                            'signType': data.signType,
                            'paySign': data.paySign,
                            'success': function (res) {
                                wx.showToast({
                                    title: '红包发送成功！',
                                })
                                that.setData({
                                    red_packet_active: false
                                })
                                that.red_packet_animation()
                                that.getinfo(that.data.id)
                            },
                            'fail': function (res) {
                            }
                        })
                    } else {
                        wx.showModal({
                            title: '失败',
                            content: res.data.msg,
                            showCancel: false
                        })
                    }
                },
                fail: function (res) {
                    wx.showToast({
                        title: '发送红包获取失败!',
                        duration: 3000
                    })
                }
            })
        }
        
    },
    
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        var that = this,
            id = that.data.id,
            title = that.data.mediadata.title,
            imageUrl = 'http://zhufucnd.xinnar.com/images/share.png'
        return {
            title: title,
            imageUrl: imageUrl,
            path: '/pages/index/blessing?id=' + id,
            success: function (res) {
                wx.showToast({
                    title: '分享成功',
                })
            },
            fail: function (res) {
                // 转发失败
            }
        }
    }
})